<template>
  <div id="map" class="map-container"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref, nextTick } from 'vue';

const props = defineProps({
  position: {
    type: String,
    default: '',
  }
});

// 解析坐标字符串为数组
const parsePositions = (positionStr: string) => {
  try {
    return positionStr.split('],[').map(coord => {
      const cleaned = coord.replace(/[\[\]]/g, '').split(',').map(Number);
      return cleaned.length === 2 && cleaned.every(num => !isNaN(num)) ? cleaned : null;
    }).filter(Boolean); // 过滤掉无效的坐标
  } catch (error) {
    console.error('坐标解析失败:', error);
    return []; // 返回空数组以避免后续错误
  }
};

const map = ref(null);
const script = ref(null);

const initMap = async () => {
  script.value = document.createElement('script');
  script.value.src = `https://webapi.amap.com/maps?v=2.0&key=9de77976f7694228b13c455472c3c5f2`;
  script.value.async = true;
  script.value.onload = async () => {
    await nextTick(); // 确保 DOM 已经完全渲染
    if (!map.value) {
      map.value = new window.AMap.Map('map', {
        center: [116.397428, 39.90923],
        zoom: 3,
      });
    }

    // 检查并添加标记
    addMarkers();
  };
  document.head.appendChild(script.value);
};

const addMarkers = () => {
  if (!map.value) {
    console.warn('地图尚未初始化');
    return;
  }

  // 判断 props.position 是否有值
  if (props.position) {
    const positions = parsePositions(props.position);

    // 仅在有有效坐标时创建标记
    if (positions.length > 0) {
      positions.forEach(position => {
        const marker = new window.AMap.Marker({
          position: position, // 标记的坐标
        });

        // 添加标记到地图
        marker.setMap(map.value);
      });
    } else {
      console.warn('没有有效的坐标可添加标记');
    }
  } else {
    console.warn('没有可用的坐标');
  }
};

const outputPositions = () => {
  console.log(props.position);
};

onMounted(() => {
  initMap();

  document.title = '农业外来入侵物种防控与管理平台';
});

// 监听 props.position 的变化
watch(() => props.position, (newVal) => {
  if (newVal && map.value) {
    addMarkers(); // 位置有变化时添加标记
  }
});

// 清理脚本元素和其他资源
onBeforeUnmount(() => {
  if (script.value) {
    document.head.removeChild(script.value);
    script.value = null;
  }
  if (map.value) {
    map.value.destroy(); // 销毁地图实例，清理资源
    map.value = null;
  }
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 500px; /* 根据需要调整高度 */
}
</style>
